import React, {useEffect, useState} from "react";
import {Avatar, Space, Card, Button, Table, message, Popconfirm,} from 'antd';
import { UserOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import axios from "axios";

const User = () =>{

    const navigate = useNavigate();
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
    const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });

    const token = window.sessionStorage.getItem("token");
    console.log("界面token:", token);
    const userId = window.sessionStorage.getItem("userId");
    console.log("userId:", userId);

    const fetchData = (current, pageSize) => {
        if (token && userId) {
            axios.get(`http://58.87.105.2:8080/video/list`, {
                headers: {
                    token: `${token}`
                },
                params: {
                    pageIndex: current,
                    pageSize: pageSize
                },
                withCredentials: true // 确保请求携带凭证
            })
                .then(response => {
                    console.log(response.data.data);
                    if (response.data.data && response.data.data.rows) {
                        // const filteredData = response.data.data.rows.filter(video => video.status === 1).map((video, index) => ({
                        //     ...video,
                        //     index: index + 1 + (current - 1) * pageSize
                        // }));
                        // setData(filteredData);
                        const filteredData = response.data.data.rows.filter(video => video.status === 1);
                        setData(filteredData);
                        setPagination({
                            current: response.data.data.pageIndex,
                            pageSize: response.data.data.pageSize,
                            total: response.data.data.total,
                        });
                        setLoading(false); // 数据加载完成，设置loading为false
                    }
                })
                .catch(error => {
                    if (error.response && error.response.status === 401) {
                        message.error("认证失败，请重新登录");
                        // navigate('/login');
                    } else {
                        message.error("获取视频列表失败");
                    }
                    setLoading(false); // 数据加载失败，也要设置loading为false
                });
        } else {
            message.error("用户未登录，请先登录！");
            setLoading(false); // 如果没有token或userId，直接设置loading为false
        }
    };

    useEffect(() => {
        fetchData(pagination.current, pagination.pageSize);
    }, [token, userId]);

    const handleTableChange = (pagination) => {
        setLoading(true);
        fetchData(pagination.current, pagination.pageSize);
    };

    const handleCardClick =()=> {
        if (!token) {
            message.warning("请先登录");
            navigate('/login');
        }
    }

    const onDelete = (record) => {
        if (token && userId) {
            axios.delete(`http://58.87.105.2:8080/video/${record.id}`, {
                headers: {
                    token: `${token}`
                },
                withCredentials: true // 确保请求携带凭证
            })
                .then(response => {
                    if (response.data.code === 0) {
                        message.success("视频删除成功");
                        // message.success("视频删除成功");
                        // setData(prevData => {
                        //     const newData = prevData.filter(item => item.id !== record.id);
                        //     return newData.map((item, index) => ({
                        //         ...item,
                        //         index: index + 1 + (pagination.current - 1) * pagination.pageSize
                        //     }));
                        // });
                        setData(prevData => prevData.filter(item => item.id !== record.id));
                    } else {
                        message.error("删除视频失败");
                    }
                })
                .catch(error => {
                    if (error.response && error.response.status === 401) {
                        message.error("认证失败，请重新登录");
                        // navigate('/login');
                    } else {
                        message.error("删除视频失败");
                    }
                });
        } else {
            message.error("用户未登录，请先登录！");
        }
    };

    const onCancel = () => {
        console.log("取消删除");
    };

    const columns = [
        {
            title: '编号',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '主题',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '视频链接',
            dataIndex: 'url',
            key: 'url',
        },
        {
            title: '点赞数量',
            dataIndex: 'likeNumber',
            key: 'likeNumber',
        },
        {
            title: '发布时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Popconfirm
                        title="删除视频"
                        description="确定删除该视频吗？"
                        onConfirm={() => onDelete(record)}
                        onCancel={onCancel}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="primary"> 删除视频 </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];


    const handleLogout =() => {
        window.sessionStorage.removeItem("userId");
        window.sessionStorage.removeItem("token");
        message.success("已退出登录");
        window.location.reload();
    }

    const cancelLogout = () => {
    }

    return(
        <div className="user-container">
            <Card className="user-info"
                  style={{height:'100px',width:'auto', alignItems:'center'}}
                  onClick={handleCardClick}>
                <Space>
                    <Avatar style={{ backgroundColor: '#87d068',marginLeft:'20px'}} size={48} icon={<UserOutlined />}/>
                    <div className="username" style={{fontSize:'24px',marginLeft:'15px'}}>
                        {userId ? userId : "未登录"}
                    </div>
                </Space>
                <Popconfirm
                    title="退出登录"
                    description="确定退出登录吗？"
                    onConfirm={handleLogout}
                    onCancel={cancelLogout}
                    okText="确定"
                    cancelText="取消"
                >
                    <Button type="link" disabled={!token}> 退出登录 </Button>
                </Popconfirm>
            </Card>
            <Card className="video-list-header"
                  style={{marginTop:'15px', fontSize:'16px', display:'flex',
                       justifyContent:'space-between', alignItems:'center'}}>
                <span style={{marginRight:'55vw'}}> 视频列表 </span>
                <Button onClick={() => navigate('/postVideo')} disabled={!token}> 发布视频 </Button>
            </Card>
            <Table
                style={{marginTop:'15px'}}
                columns={columns}
                dataSource={data}
                loading={loading}
                pagination={{
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                    total: pagination.total,
                }}
                onChange={handleTableChange}
                scroll={{ x: 'max-content' }} // 允许表格横向滚动
            />
        </div>
    )
};

export default User;
